# user/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
from rest_framework_simplejwt.tokens import RefreshToken, OutstandingToken, BlacklistedToken
from .serializers import LoginSerializer, UserSerializer, UserUpdateSerializer, UserListSerializer
from .models import User
from django.core.exceptions import ObjectDoesNotExist


class LoginView(APIView):
    permission_classes = [AllowAny]  # 登录接口不需要认证

    def post(self, request):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            user = serializer.validated_data['user']

            # 生成JWT令牌
            refresh = RefreshToken.for_user(user)

            # 构造响应数据
            data = {
                'success': True,
                'data': {
                    'accessToken': str(refresh.access_token),
                    'refreshToken': str(refresh),
                    'user': UserSerializer(user).data
                }
            }

            return Response(data, status=status.HTTP_200_OK)
        else:
            data = {
                'success': False,
                'message': '验证失败'
            }

            # 将序列化器的错误信息合并到message中
            errors = serializer.errors
            if errors:
                error_messages = []
                for field, messages in errors.items():
                    error_messages.extend(messages)
                data['message'] = ' '.join(error_messages)

            return Response(data, status=status.HTTP_400_BAD_REQUEST)


class RefreshTokenView(APIView):
    permission_classes = [AllowAny]  # 刷新令牌接口不需要认证

    def post(self, request):
        refresh_token = request.data.get('refreshToken')

        if not refresh_token:
            return Response({
                'success': False,
                'message': '刷新令牌不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 验证刷新令牌
            refresh = RefreshToken(refresh_token)

            # 生成新的访问令牌
            access_token = refresh.access_token

            data = {
                'success': True,
                'data': {
                    'accessToken': str(access_token)
                }
            }

            return Response(data, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                'success': False,
                'message': '无效的刷新令牌'
            }, status=status.HTTP_401_UNAUTHORIZED)


class UserInfoView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        serializer = UserSerializer(user)

        data = {
            'success': True,
            'data': serializer.data
        }

        return Response(data, status=status.HTTP_200_OK)


class LogoutView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            refresh_token = request.data.get('refreshToken')

            if refresh_token:
                token = RefreshToken(refresh_token)
                token.blacklist()

            return Response({
                'success': True,
                'message': '已退出登录'
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                'success': False,
                'message': '退出登录失败'
            }, status=status.HTTP_400_BAD_REQUEST)


# 注册接口
class RegisterView(APIView):
    permission_classes = [AllowAny]  # 注册接口不需要认证

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        # 参数验证
        if not username or not password:
            return Response({
                'success': False,
                'message': '用户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 用户名长度验证
        if len(username) < 3 or len(username) > 20:
            return Response({
                'success': False,
                'message': '用户名长度必须在3-20个字符之间'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 密码长度验证
        if len(password) < 6 or len(password) > 20:
            return Response({
                'success': False,
                'message': '密码长度必须在6-20个字符之间'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return Response({
                'success': False,
                'message': '用户名已存在'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 创建用户
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                role='admin'  # 默认为管理员
            )
            user.is_staff = True  # 确保管理员可以在Django后台管理
            user.save()

            return Response({
                'success': True,
                'message': '注册成功'
            }, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({
                'success': False,
                'message': '注册失败'
            }, status=status.HTTP_400_BAD_REQUEST)


# 修改用户信息接口
class UserUpdateView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request):
        # 检查是否是管理员
        is_admin = request.user.role == 'admin'

        # 获取要更新的用户ID
        user_id = request.data.get('id')

        # 如果不是管理员且试图更新其他用户的信息，则拒绝
        if not is_admin and user_id and int(user_id) != request.user.id:
            return Response({
                'success': False,
                'message': '权限不足，无法更新其他用户信息'
            }, status=status.HTTP_403_FORBIDDEN)

        # 如果不是管理员且试图更新角色，则拒绝
        if not is_admin and 'role' in request.data:
            return Response({
                'success': False,
                'message': '权限不足，无法更新用户角色'
            }, status=status.HTTP_403_FORBIDDEN)

        # 管理员可以更新任何用户的信息
        if is_admin and user_id:
            try:
                user = User.objects.get(id=user_id)
            except ObjectDoesNotExist:
                return Response({
                    'success': False,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)
        else:
            # 普通用户只能更新自己的信息
            user = request.user

        serializer = UserUpdateSerializer(user, data=request.data, partial=True)

        if serializer.is_valid():
            serializer.save()
            return Response({
                'success': True,
                'message': '用户信息更新成功',
                'data': UserSerializer(user).data
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': '更新失败',
                'errors': serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)


# 获取用户列表接口
class UserListView(APIView):
    permission_classes = [IsAuthenticated, IsAdminUser]  # 只有登录的账号可以访问

    def get(self, request):
        users = User.objects.all()
        serializer = UserListSerializer(users, many=True)

        return Response({
            'success': True,
            'data': serializer.data
        }, status=status.HTTP_200_OK)


# 删除用户接口
class UserDeleteView(APIView):
    permission_classes = [IsAuthenticated, IsAdminUser]  # 只有管理员可以访问

    def delete(self, request, user_id):
        try:
            # 不能删除自己
            if request.user.id == user_id:
                return Response({
                    'success': False,
                    'message': '不能删除自己的账户'
                }, status=status.HTTP_400_BAD_REQUEST)

            user = User.objects.get(id=user_id)
            user.delete()

            return Response({
                'success': True,
                'message': '用户删除成功'
            }, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return Response({
                'success': False,
                'message': '用户不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'success': False,
                'message': '删除失败'
            }, status=status.HTTP_400_BAD_REQUEST)
